/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.product.rest;

import cn.hutool.core.bean.BeanUtil;
import link.chengguo.orangemall.constant.ShopConstants;
import link.chengguo.orangemall.enums.ShopCommonEnum;
import link.chengguo.orangemall.enums.SpecTypeEnum;
import link.chengguo.orangemall.logging.aop.log.Log;
import link.chengguo.orangemall.modules.aop.ForbidSubmit;
import link.chengguo.orangemall.modules.category.domain.OrangeStoreCategory;
import link.chengguo.orangemall.modules.category.service.OrangeStoreCategoryService;
import link.chengguo.orangemall.modules.product.domain.OrangeStoreProduct;
import link.chengguo.orangemall.modules.product.domain.OrangeStoreProductAttrResult;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductAttrResultService;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductRuleService;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductService;
import link.chengguo.orangemall.modules.product.service.dto.ProductDto;
import link.chengguo.orangemall.modules.product.service.dto.ProductFormatDto;
import link.chengguo.orangemall.modules.product.service.dto.StoreProductDto;
import link.chengguo.orangemall.modules.product.service.dto.OrangeStoreProductQueryCriteria;
import link.chengguo.orangemall.modules.template.domain.OrangeShippingTemplates;
import link.chengguo.orangemall.modules.template.service.OrangeShippingTemplatesService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
* @author chengguo
* @date 2019-10-04
*/
@Api(tags = "商城:商品管理")
@RestController
@RequestMapping("api")
public class StoreProductController {

    private final OrangeStoreProductService orangeStoreProductService;
    private final OrangeStoreCategoryService orangeStoreCategoryService;
    private final OrangeShippingTemplatesService orangeShippingTemplatesService;
    private final OrangeStoreProductRuleService orangeStoreProductRuleService;
    private final OrangeStoreProductAttrResultService orangeStoreProductAttrResultService;

    public StoreProductController(OrangeStoreProductService orangeStoreProductService,
                                  OrangeStoreCategoryService orangeStoreCategoryService,
                                  OrangeShippingTemplatesService orangeShippingTemplatesService,
                                  OrangeStoreProductRuleService orangeStoreProductRuleService,
                                  OrangeStoreProductAttrResultService orangeStoreProductAttrResultService) {
        this.orangeStoreProductService = orangeStoreProductService;
        this.orangeStoreCategoryService = orangeStoreCategoryService;
        this.orangeShippingTemplatesService = orangeShippingTemplatesService;
        this.orangeStoreProductRuleService = orangeStoreProductRuleService;
        this.orangeStoreProductAttrResultService = orangeStoreProductAttrResultService;
    }

    @Log("查询商品")
    @ApiOperation(value = "查询商品")
    @GetMapping(value = "/orangeStoreProduct")
    @PreAuthorize("hasAnyRole('admin','ORANGESTOREPRODUCT_ALL','ORANGESTOREPRODUCT_SELECT')")
    public ResponseEntity getOrangeStoreProducts(OrangeStoreProductQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(orangeStoreProductService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @ForbidSubmit
    @Log("新增/修改商品")
    @ApiOperation(value = "新增/修改商品")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PostMapping(value = "/orangeStoreProduct/addOrSave")
    @PreAuthorize("hasAnyRole('admin','ORANGESTOREPRODUCT_ALL','ORANGESTOREPRODUCT_CREATE')")
    public ResponseEntity create(@Validated @RequestBody StoreProductDto storeProductDto){
        orangeStoreProductService.insertAndEditOrangeStoreProduct(storeProductDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }


    @ForbidSubmit
    @Log("删除商品")
    @ApiOperation(value = "删除商品")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @DeleteMapping(value = "/orangeStoreProduct/{id}")
    @PreAuthorize("hasAnyRole('admin','ORANGESTOREPRODUCT_ALL','ORANGESTOREPRODUCT_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        orangeStoreProductService.removeById(id);
        return new ResponseEntity(HttpStatus.OK);
    }



    @ApiOperation(value = "商品上架/下架")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PostMapping(value = "/orangeStoreProduct/onsale/{id}")
    public ResponseEntity onSale(@PathVariable Long id,@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Integer status = jsonObject.getInteger("status");
        orangeStoreProductService.onSale(id,status);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "生成属性")
    @PostMapping(value = "/orangeStoreProduct/isFormatAttr/{id}")
    public ResponseEntity isFormatAttr(@PathVariable Long id,@RequestBody String jsonStr){
        return new ResponseEntity<>(orangeStoreProductService.getFormatAttr(id,jsonStr),HttpStatus.OK);
    }



    @ApiOperation(value = "获取商品信息")
    @GetMapping(value = "/orangeStoreProduct/info/{id}")
    public ResponseEntity info(@PathVariable Long id){
        Map<String,Object> map = new LinkedHashMap<>(3);

        //运费模板
        List<OrangeShippingTemplates> shippingTemplatesList = orangeShippingTemplatesService.list();
        map.put("tempList", shippingTemplatesList);

        //商品分类
        List<OrangeStoreCategory> storeCategories = orangeStoreCategoryService.lambdaQuery()
                .eq(OrangeStoreCategory::getIsShow, ShopCommonEnum.SHOW_1.getValue())
                .list();

        List<Map<String,Object>> cateList = new ArrayList<>();
        map.put("cateList", this.makeCate(storeCategories,cateList,0,1));

        //商品规格
        map.put("ruleList", orangeStoreProductRuleService.list());


        if(id == 0){
            return new ResponseEntity<>(map,HttpStatus.OK);
        }

        //处理商品详情
        OrangeStoreProduct orangeStoreProduct = orangeStoreProductService.getById(id);
        ProductDto productDto = new ProductDto();
        BeanUtil.copyProperties(orangeStoreProduct,productDto,"sliderImage");
        productDto.setSliderImage(Arrays.asList(orangeStoreProduct.getSliderImage().split(",")));
        OrangeStoreProductAttrResult storeProductAttrResult = orangeStoreProductAttrResultService
                .getOne(Wrappers.<OrangeStoreProductAttrResult>lambdaQuery()
                        .eq(OrangeStoreProductAttrResult::getProductId,id).last("limit 1"));
        JSONObject result = JSON.parseObject(storeProductAttrResult.getResult());

        if(SpecTypeEnum.TYPE_1.getValue().equals(orangeStoreProduct.getSpecType())){
            productDto.setAttr(new ProductFormatDto());
            productDto.setAttrs(result.getObject("value",ArrayList.class));
            productDto.setItems(result.getObject("attr",ArrayList.class));
        }else{
            Map<String,Object> mapAttr = (Map<String,Object>)result.getObject("value",ArrayList.class).get(0);
            ProductFormatDto productFormatDto = ProductFormatDto.builder()
                    .pic(mapAttr.get("pic").toString())
                    .price(Double.valueOf(mapAttr.get("price").toString()))
                    .cost(Double.valueOf(mapAttr.get("cost").toString()))
                    .otPrice(Double.valueOf(mapAttr.get("ot_price").toString()))
                    .stock(Integer.valueOf(mapAttr.get("stock").toString()))
                    .vipPrice(mapAttr.get("vipPrice").toString())
                    .barCode(mapAttr.get("bar_code").toString())
                    .weight(Double.valueOf(mapAttr.get("weight").toString()))
                    .volume(Double.valueOf(mapAttr.get("volume").toString()))
                    .brokerage(Double.valueOf(mapAttr.get("brokerage").toString()))
                    .brokerageTwo(Double.valueOf(mapAttr.get("brokerage_two").toString()))
                    .build();
            productDto.setAttr(productFormatDto);
        }


        map.put("productInfo",productDto);

        return new ResponseEntity<>(map,HttpStatus.OK);
    }


    /**
     *  分类递归
     * @param data 分类列表
     * @param pid 附件id
     * @param level d等级
     * @return list
     */
    private List<Map<String,Object>> makeCate(List<OrangeStoreCategory> data, List<Map<String,Object>> cateList, int pid, int level)
    {
        String html = "|-----";
        String newHtml = "";

        for (int i = 0; i < data.size(); i++) {
            OrangeStoreCategory storeCategory = data.get(i);
            int catePid =  storeCategory.getPid();
            Map<String,Object> map = new HashMap<>();
            if(catePid == pid){
                newHtml = String.join("", Collections.nCopies(level,html));
                map.put("value",storeCategory.getId());
                map.put("label",newHtml + storeCategory.getCateName());
                if(storeCategory.getPid() == 0){
                    map.put("disabled",0);
                }else{
                    map.put("disabled",1);
                }
                cateList.add(map);
                data.remove(i);

                i--;
                this.makeCate(data,cateList,storeCategory.getId(),level + 1);
            }
        }


        return cateList;
    }






}
